package com.share.filter;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.share.function.bean.UserBean;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter("*.action")
public class LoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public LoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 向下强制转型
		HttpServletRequest req = (HttpServletRequest) request;
		// 得到基本路径
		String path = req.getContextPath();
		// 得到请求地址
		String uri = req.getRequestURI();
		// 登录相关直接通过
		if (uri.startsWith(path + "/login/")) {
			chain.doFilter(req, response);
			System.out.println("LoginFilter.login.path--" + path + "--uri--" + uri);
			return;
		}
		// 判断当前用户是否登录
		HttpSession session = req.getSession();
		// 得到当前用户
		UserBean loginUser = (UserBean) session.getAttribute("loginUser");
		System.out.println("loginUser是否为空" + (null == loginUser));
		// 若当前用户为空判定为未登录
		if (null == loginUser) {
			System.out.println(uri);
			req.getRequestDispatcher("../jsp/login/logout.jsp").forward(req, response);
			return;
		}
		// 得到当前用户的权限列表
		List<Map<String, Object>> powerList = loginUser.getPowerList();
		for (Map<String, Object> power : powerList) {
			String sUrl = (String) power.get("sUrl");
			System.out.println("LoginFilter.login.sUrl--" + sUrl);
			if (sUrl.length() == 0) {
				continue;
			}
			int index = sUrl.indexOf("/");
			if (index != -1) {
				// 截取“/”前的字符串
				sUrl = sUrl.substring(0, index);
			}
			sUrl = path + "/" + sUrl;
			// 判断权限是否合法
			if (uri.startsWith(sUrl)) {
				chain.doFilter(req, response);
				return;
			}
		}
		System.out.println("LoginFilter.login.uri--" + uri);
		req.setAttribute("msg", "你的请求不合法");
		req.getRequestDispatcher("/html/error.html").forward(req, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
